/*
 * Copyright 2013 Akihiko Nakagawa
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jp.fsoriented.toishi;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import jp.fsoriented.toishi.data.AnmitsuData;
import jp.fsoriented.toishi.data.Verse;
import jp.fsoriented.toishi.data.VerseDateComparator;
import jp.fsoriented.toishi.data.VerseLocationComparator;
import jp.fsoriented.toishi.data.VerseOkCountComparator;
import jp.fsoriented.toishi.util.L;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class MainActivity extends SherlockActivity implements AdapterView.OnItemClickListener {

	private VerseAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		L.onCreate("Main");
		setContentView(R.layout.activity_main);
		adapter = new VerseAdapter(this, new ArrayList<Verse>());
		ListView listview = (ListView) findViewById(R.id.activity_main_list);
		listview.setAdapter(adapter);
		listview.setOnItemClickListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		L.onResume("Main");

		// リストビューの内容を、あんみつデータと同期させる
		AnmitsuData.getInstance().load(this);
		syncListData();
	}

	@Override
	protected void onPause() {
		super.onPause();
		L.onPause("Main");
		// あんみつデータを保存
		AnmitsuData.getInstance().store(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		L.onDestroy("Main");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		AnmitsuData data = AnmitsuData.getInstance();
		switch (id) {
		case R.id.menu_main_actionbar_about:
			L.d("About selected.");
			AboutToishiActivity.start(this);
			break;
		case R.id.menu_main_actionbar_add_verse:
			L.d("Add Verse selected.");
			InputActivity.startInputType(this);
			break;
		case R.id.menu_main_actionbar_sort_added:
			L.d("Sort - Added selected.");
			Collections.sort(data.verses, new VerseDateComparator());
			syncListData();
			break;
		case R.id.menu_main_actionbar_sort_location:
			L.d("Sort - Location selected.");
			Collections.sort(data.verses, new VerseLocationComparator());
			syncListData();
			break;
		case R.id.menu_main_actionbar_sort_yet_mind:
			L.d("Sort - Not minded selected.");
			Collections.sort(data.verses, new VerseOkCountComparator());
			syncListData();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// リストのアイテムがクリックされたら、インデックスの御言葉を開く
		TestActivity.start(this, position);
	}

	private void syncListData() {
		adapter.clear();
		List<Verse> verses = AnmitsuData.getInstance().verses;
		for (Verse v : verses) {
			adapter.add(v);
		}
	}

	/**
	 * VerseAdapterで使われるビュー（一行分）を保持する。
	 *
	 * ビューにタグとして登録し、表示を高速化する。
	 */
	class VerseHolder {

		public TextView top;
		public TextView bottom;
		public ImageView left;

	}

	/**
	 * みことば一覧の要素・ビュー
	 */
	class VerseAdapter extends ArrayAdapter<Verse> {

		private LayoutInflater inflater;
		private List<Verse> list;
		private final SimpleDateFormat form;

		/**
		 * コンストラクタ
		 *
		 * @param context
		 * @param textViewResourceId
		 * @param objects
		 */
		public VerseAdapter(Context context, List<Verse> objects) {
			super(context, R.layout.activity_main_list_row, objects);
			list = objects;
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			form = new SimpleDateFormat();
		}

		/**
		 * ビューを作成する
		 */
		public View getView(final int position, View convertView, final ViewGroup parent) {
			VerseHolder holder = null;
			// 新規行ビュー作成。または既存のビューを取得。
			View v = convertView;
			if (v == null) {
				v = inflater.inflate(R.layout.activity_main_list_row, null);
				holder = new VerseHolder();
				holder.top = (TextView) v.findViewById(R.id.activity_main_list_above_text);
				holder.bottom = (TextView) v.findViewById(R.id.activity_main_list_below_text);
				holder.left = (ImageView) v.findViewById(R.id.activity_main_list_left_image);
				v.setTag(holder);
			} else {
				holder = (VerseHolder) v.getTag();
			}
			// 行データ適用
			if ((list != null) && (list.size() > position)) {
				Verse item = list.get(position);
				holder.top.setText(item.getLocationName());
				holder.left.setBackgroundResource(getStatusIconId(item.okCount, item.result.size()));
				holder.bottom.setText(item.result.size() + "回中" + item.okCount + "回成功 追加："
						+ form.format(item.addedDate));
			}
			return v;
		}

		private int getStatusIconId(int success, int all) {
			if (all == 0) {
				return R.drawable.activity_main_drawable_red;
			} else if (success == 0) {
				return R.drawable.activity_main_drawable_yellow;
			} else {
				return R.drawable.activity_main_drawable_green;
			}
		}

	}

}
